<template>
    <div class="meter-report-container">
        <!-- 日期选择和导出区域 -->
        <div class="meter-report-header">
            <CustomDatePicker :maxDays="365 * 2" border :is-month-picker="true" round v-model="dateRange" />
            <el-button style="margin-left: auto;" type="success" :loading="isExporting" @click="handleExport">
                <template #icon>
                    <i class="fa fa-download"></i>
                </template>
                导出
            </el-button>
        </div>

        <!-- 表格区域 -->
        <vxe-table ref="tableRef" height="92%" v-loading="isLoading" border align="center" :data="meterTableData"
            :tree-config="treeConfig" :export-config="exportConfig">
            <!-- 固定列 -->
            <vxe-column type="seq" width="60" />
            <vxe-column fixed="left" tree-node field="meter_code" title="表计编号" width="120" />
            <vxe-column width="100" show-overflow="tooltip" title="区域">
                <template #default="{ row }">
                    {{ areaStore.getAreaNameById(row.area_id) || '-' }}
                </template>
            </vxe-column>
            <vxe-column width="120" show-overflow="tooltip" field="installation_location" title="安装位置" />
            <vxe-column field="specification" width="100" title="规格" />
            <vxe-column width="100" field="startReading" title="启读数"></vxe-column>
            <!-- 动态日期列 -->
            <vxe-colgroup v-for="(date, dateIndex) in dateColumns" :key="date" :title="date">
                <vxe-column width="100" :field="`usage_${dateIndex}`" title="用量">
                    <template #default="{ row }">
                        {{ formatFlowValue(row[`usage_${dateIndex}`]) }}
                    </template>
                    <template #footer="{ row }">
                        {{ formatFlowValue(row[`usage_${dateIndex}`]) }}
                    </template>
                </vxe-column>
                <vxe-column width="100" :field="`reading_${dateIndex}`" title="读数">
                    <template #default="{ row }">
                        {{ formatReadingValue(row[`reading_${dateIndex}`]) }}
                    </template>
                </vxe-column>
            </vxe-colgroup>

            <!-- 总流量列 -->
            <vxe-column fixed="right" field="sum" width="100" title="总用量" />
        </vxe-table>
    </div>

</template>

<script setup>
import { ref, onMounted, watch, computed, reactive } from "vue";
import dayjs from "dayjs";
import { getMeterReportApi } from "@/api/meter";
import CustomDatePicker from "@/components/header/CustomDatePicker.vue";
import { useMeterStore } from "@/stores/meter";
import { useAreaStore } from "@/stores/area";
import { formatFlowValue, formatReadingValue, generateDateColumns, transformMeterData } from "@/utils/meterUtils";

// 状态管理
const meterStore = useMeterStore();
const areaStore = useAreaStore();

// 组件引用
const tableRef = ref(null);

// 响应式数据
const dateRange = ref([
    dayjs().startOf("year").valueOf(),
    dayjs().startOf("day").valueOf(),
]);

const exportConfig = {
    type: 'xlsx',
    includeFooter: true,
    useStyle: true,
    isFooter: true,
    isColgroup: true,
    isAllExpand: true,
    // 分组表头
    filename: '气表月统计报表',
    sheetName: '表计报表',
    modes: ['current']
}

const meterTableData = ref([]);


const isLoading = ref(false);
const isExporting = ref(false);

// 树形配置
const treeConfig = reactive({
    transform: true,
    rowField: "id",
    parentField: "parent_id",
    lazy: true,
    hasChild: "hasChild",
    showLine: true,
    loadMethod: ({ row }) => loadChildNodes(row),
});

// 计算属性：日期列
const dateColumns = computed(() => {
    return generateDateColumns(dateRange.value[0], dateRange.value[1], 'month');
});

async function fetchMeterReport() {
    if (isLoading.value) return;

    try {
        meterTableData.value = [];
        isLoading.value = true;

        const promises = meterStore.treeDataForChart.map(meter =>
            fetchAndProcessMeterData(meter)
        );

        const results = await Promise.all(promises);
        meterTableData.value = results.filter(Boolean);

    } catch (error) {
        ElNotification({
            type: 'error',
            title: 'Error',
            message: error.message || '获取气表数据失败'
        })
        console.error('Failed to fetch meter report:', error);
    } finally {
        isLoading.value = false;
    }
}

/**
 * 获取并处理单个表计数据
 * @param {Object} meter - 表计信息
 * @returns {Promise<Object>} 处理后的表计数据
 */
async function fetchAndProcessMeterData(meter) {
    try {
        const response = await getMeterReportApi({
            id: meter.id,
            start_time: dateRange.value[0],
            end_time: dayjs(dateRange.value[1]).valueOf(),
            interval: 'month',
        });

        return transformMeterData(meter, response);
    } catch (error) {
        ElNotification({
            type: 'error',
            title: 'Error',
            message: error.message || '获取气表数据失败'
        })
        console.error(`Failed to fetch data for meter ${meter.meter_code}:`, error);
        return null;
    }
}

const showUnknownRate = ref(false);
async function loadChildNodes(parentNode) {
    try {
        const promises = parentNode.customChildren.map(child =>
            fetchAndProcessMeterData(child)
        );

        const children = await Promise.all(promises);
        const validChildren = children.filter(Boolean);

        return validChildren;
    } catch (error) {
        ElNotification({
            type: 'error',
            title: 'Error',
            message: error.message || '获取气表数据失败'
        })
        console.error('Failed to load child nodes:', error);
        return [];
    }
}

async function handleExport() {
    try {
        isExporting.value = true;
        const table = tableRef.value;

        // 展开所有节点
        for (let i = 0; i < meterStore.meterLevels.length; i++) {
            await table?.setAllTreeExpand(true);
        }
        // 设置导出选项
        await table?.openExport({
            includeFooter: true
        });

    } finally {
        isExporting.value = false;
    }
}

// 监听数据变化
watch(
    [() => dateRange.value, () => meterStore.treeDataForChart],
    () => {
        fetchMeterReport();
    },
    { deep: true }
);

watch(
    [() => showUnknownRate.value],
    () => {
        fetchMeterReport();
    },
    { deep: true }
);

// 生命周期钩子
onMounted(async () => {
    if (!meterStore.treeDataForChart.length || meterStore.currentSelectedType !== 3) {
        meterStore.setCurrentSelectedType(3);
        await meterStore.fetchMeterList();
    }
    fetchMeterReport();
});
</script>

<style scoped>
.meter-report-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.meter-report-header {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
}

.meter-report-body {
    flex: 1;
}
</style>